import axios from 'axios'
import { 
    API_CONFIG, 
    USER_ROUTES, 
    BUSINESS_ROUTES, 
    FOOD_ROUTES, 
    CART_ROUTES, 
    ORDER_ROUTES, 
    ADDRESS_ROUTES,
    REFUND_ROUTES,
    WALLET_ROUTES,
    IMAGE_ROUTES 
} from './routes'


// API基础配置
const api = axios.create({
    baseURL: API_CONFIG.BASE_URL, // 后端服务器地址
    timeout: API_CONFIG.TIMEOUT, // 请求超时时间
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器 - 用于自动附加JWT Token
api.interceptors.request.use(
    config => {
        // 从 localStorage 中获取 token
        // 这是最简单的方式，更好的方式是在 pinia store 初始化时从 localStorage 读取
        const token = localStorage.getItem('jwt-token');

        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`;
        }
        
        // 移除旧的 qs.stringify 逻辑
        return config
    },
    error => {
        console.error('请求错误:', error)
        return Promise.reject(error)
    }
)

// 响应拦截器 - 用于统一处理数据结构和错误
api.interceptors.response.use(
    response => {
        // 检查是否是登录接口响应，登录接口的JWT直接返回
        if (response.config.url.includes('/api/auth')) {
            return response.data;
        }

        // Spring Boot 的 HttpResult 包装了响应
        const res = response.data;
        
        // 检查响应数据格式
        if (res === null || res === undefined) {
            return null;
        }
        
        // 如果响应是数组或原始值，直接返回
        if (Array.isArray(res) || typeof res !== 'object' || res === null) {
            return res;
        }
        
        // 如果返回包含success字段，则按HttpResult处理
        if ('success' in res) {
            if (res.success) {
                return res.data;
            } else {
                console.error('API业务错误:', res.message);
                return Promise.reject(new Error(res.message || '操作失败'));
            }
        } 
        
        // 否则直接返回响应数据
        return res;
    },
    error => {
        // 处理 HTTP 层面错误
        console.error('API响应错误:', error.response?.status, error.config?.url)

        // 统一错误处理
        let errorMessage = '请求失败'
        if (error.response) {
            switch (error.response.status) {
                case 400:
                    errorMessage = '请求参数错误'
                    break
                case 401:
                    errorMessage = '未授权，请重新登录'
                    break
                case 403:
                    errorMessage = '拒绝访问'
                    break
                case 404:
                    errorMessage = '请求的资源不存在'
                    break
                case 500:
                    errorMessage = '服务器内部错误，请稍后重试'
                    break
                default:
                    errorMessage = `请求失败 (${error.response.status})`
            }
            
            // 检查错误响应中是否有详细信息
            const data = error.response.data;
            if (data && typeof data === 'object') {
                if (data.message) {
                    errorMessage = data.message;
                } else if (data.error) {
                    errorMessage = data.error;
                }
            }
        } else if (error.request) {
            errorMessage = '网络连接失败，请检查网络'
        }

        return Promise.reject(new Error(errorMessage))
    }
)

// 用户相关API
export const userApi = {
    // 用户登录
    login(username, password) {
        return api.post(USER_ROUTES.LOGIN, { username, password })
    },

    // 用户注册
    register(userInfo) {
        return api.post(USER_ROUTES.REGISTER, userInfo)
    },

    // 检查用户名是否存在
    checkUsername(username) {
        return api.get(USER_ROUTES.CHECK_USERNAME, { params: { username } })
    },
    
    // 检查手机号是否存在
    checkPhoneNumber(phoneNumber) {
        return api.get('/api/users/check-phone', { params: { phoneNumber } })
    },

    // 获取当前用户信息
    getCurrentUser() {
        return api.get(USER_ROUTES.GET_CURRENT_USER)
    },

    // 更新用户信息
    updateUser(userInfo) {
        return api.post('/api/password', {
            username: userInfo.username,
            password: userInfo.newPassword
        })
    }
}

// 商家相关API
export const businessApi = {
    // 获取所有商家列表 (可以接受参数，如排序、分类)
    getBusinessList(params) { // params 可以是 { category: '快餐' }
        return api.get(BUSINESS_ROUTES.LIST_BUSINESS, { params })
    },

    // 根据ID获取商家信息
    getBusinessById(businessId) {
        return api.get(`${BUSINESS_ROUTES.GET_BUSINESS_BY_ID}/${businessId}`)
    },
    
    // 删除商家（软删除）
    deleteBusiness(businessId) {
        return api.delete(`${BUSINESS_ROUTES.GET_BUSINESS_BY_ID}/${businessId}`)
    }
}

// 食品相关API
export const foodApi = {
    // 根据商家ID获取食品列表, 使用查询参数而不是路径参数
    getFoodListByBusinessId(businessId) {
        return api.get(FOOD_ROUTES.LIST_FOOD_BY_BUSINESS_ID, {
            params: { business: businessId }
        });
    }
}

// 图片上传相关API
export const imageApi = {
    // 上传商家图片
    uploadBusinessImage(file, businessId = null) {
        // 创建FormData对象，用于上传文件
        const formData = new FormData();
        formData.append('file', file);
        
        // 如果提供了businessId，添加到请求中
        if (businessId) {
            formData.append('businessId', businessId);
        }
        
        // 创建特殊的请求配置，用于文件上传
        const config = {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        };
        
        return api.post(IMAGE_ROUTES.UPLOAD_BUSINESS_IMAGE, formData, config);
    },
    
    // 上传食品图片
    uploadFoodImage(file, foodId = null) {
        // 创建FormData对象，用于上传文件
        const formData = new FormData();
        formData.append('file', file);
        
        // 如果提供了foodId，添加到请求中
        if (foodId) {
            formData.append('foodId', foodId);
        }
        
        // 创建特殊的请求配置，用于文件上传
        const config = {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        };
        
        return api.post(IMAGE_ROUTES.UPLOAD_FOOD_IMAGE, formData, config);
    },
    
    // 获取商家图片二进制数据
    getBusinessImageBinary(businessId) {
        // 添加时间戳参数避免浏览器缓存
        const timestamp = new Date().getTime();
        const url = `${API_CONFIG.BASE_URL}/api/images/business-binary/${businessId}?t=${timestamp}`;
        console.log(`尝试加载商家图片二进制数据，URL=${url}, businessId=${businessId}`);
        return url;
    },
    
    // 获取食品图片二进制数据
    getFoodImageBinary(foodId) {
        const url = `${API_CONFIG.BASE_URL}/api/images/food-binary/${foodId}`;
        console.log(`尝试加载食品图片二进制数据，URL=${url}, foodId=${foodId}`);
        return url;
    }
}

// 购物车相关API
export const cartApi = {
    // 获取购物车列表, 方法为 GET，可选参数businessId用于过滤特定商家的购物车
    getCartList(businessId) {
        const params = businessId ? { businessId } : {};
        return api.get(CART_ROUTES.LIST_CART, { params });
    },

    // 添加到购物车, cartInfo 中应包含 foodId 和 quantity
    addToCart(cartInfo) {
        return api.post(CART_ROUTES.SAVE_CART, cartInfo)
    },

    // 更新购物车, 方法应为 PUT，用于更新
    updateCart(cartInfo) {
        return api.put(CART_ROUTES.UPDATE_CART, cartInfo)
    },

    // 从购物车移除, 方法应为 DELETE，要删除的商品信息在请求体中
    removeFromCart(cartInfo) { // cartInfo 可能只需要 { foodId }
        return api.delete(CART_ROUTES.REMOVE_CART, { data: cartInfo });
    }
}

// 订单相关API
export const orderApi = {
    // 创建订单, orderInfo 包含创建订单所需的数据
    createOrder(orderInfo) {
        return api.post(ORDER_ROUTES.CREATE_ORDER, orderInfo)
    },

    // 获取用户订单列表, 方法为 GET，无需 userId，服务器通过 token 识别
    getOrderList() {
        return api.get(ORDER_ROUTES.LIST_MY_ORDERS)
    },
    
    // 获取订单基本信息，根据ID
    getOrderById(orderId) {
        return api.get(`${ORDER_ROUTES.GET_ORDER_DETAIL}/${orderId}`);
    },
    
    // 获取订单的商品详情，根据订单ID
    getOrderDetailets(orderId) {
        return api.get(`${ORDER_ROUTES.GET_ORDER_DETAILETS}/${orderId}/detailets`);
    },
    
    // 更新订单状态
    updateOrderStatus(orderId, status) {
        console.log(`调用updateOrderStatus API: orderId=${orderId}, status=${status}`);
        return api.put(`${ORDER_ROUTES.CREATE_ORDER}/${orderId}/status?status=${status}`);
    },
    
    // 取消订单 (实际上是调用更新状态API，将状态设为0表示取消)
    cancelOrder(orderId) {
        console.log(`调用cancelOrder API: orderId=${orderId}`);
        return api.put(`${ORDER_ROUTES.CREATE_ORDER}/${orderId}/status?status=0`);
    }
}

// 退款相关API
export const refundApi = {
    // 申请退款
    applyRefund(orderId, refundData = {}) {
        return api.post(`${REFUND_ROUTES.APPLY_REFUND}/${orderId}`, refundData);
    },
    
    // 商家处理退款申请
    processRefund(refundId, approved, rejectReason = '') {
        return api.post(`${REFUND_ROUTES.PROCESS_REFUND}/${refundId}/process`, {
            approved,
            rejectReason
        });
    },
    
    // 检查订单是否可以退款
    checkRefundEligibility(orderId) {
        return api.get(`${REFUND_ROUTES.CHECK_REFUND_ELIGIBILITY}/${orderId}/eligibility`);
    },
    
    // 获取订单的退款申请
    getRefundByOrderId(orderId) {
        return api.get(`${REFUND_ROUTES.APPLY_REFUND}/order/${orderId}`);
    },
    
    // 获取商家的所有退款申请
    getRefundsByBusinessId(businessId) {
        return api.get(`${REFUND_ROUTES.APPLY_REFUND}/business/${businessId}`);
    },
    
    // 获取所有待处理的退款申请
    getPendingRefunds() {
        return api.get(`${REFUND_ROUTES.APPLY_REFUND}/pending`);
    },
    
    // 获取订单的退款详情信息
    getRefundDetailsByOrderId(orderId) {
        return api.get(`${REFUND_ROUTES.APPLY_REFUND}/details/order/${orderId}`);
    }
}

export const walletApi = {
    getMyWallet() {
        return api.get(WALLET_ROUTES.BASE)
    },
    createWallet() {
        return api.post(WALLET_ROUTES.BASE)
    },
    recharge({ amount, remark, businessId } = {}) {
        return api.post(WALLET_ROUTES.RECHARGE, { amount, remark, businessId })
    },
    withdraw({ amount, remark } = {}) {
        return api.post(WALLET_ROUTES.WITHDRAW, { amount, remark })
    },
    pay({ amount, orderId, remark } = {}) {
        return api.post(WALLET_ROUTES.PAY, { amount, orderId, remark })
    },
    refund({ amount, orderId, remark, includeFrozen } = {}) {
        return api.post(WALLET_ROUTES.REFUND, { amount, orderId, remark, includeFrozen })
    },
    freeze({ amount, orderId, remark } = {}) {
        return api.post(WALLET_ROUTES.FREEZE, { amount, orderId, remark })
    },
    unfreeze({ amount, orderId, remark } = {}) {
        return api.post(WALLET_ROUTES.UNFREEZE, { amount, orderId, remark })
    },
    transfer({ amount, targetPhoneNumber, orderId, remark } = {}) {
        return api.post(WALLET_ROUTES.TRANSFER, { amount, targetPhoneNumber, orderId, remark })
    },
    checkBalanceSufficient(amount) {
        return api.get(WALLET_ROUTES.BALANCE_SUFFICIENT, { params: { amount } })
    },
    listTransactions({ page = 0, size = 20, sort = 'createTime,desc' } = {}) {
        return api.get(WALLET_ROUTES.TRANSACTIONS, { params: { page, size, sort } })
    },
    listTransactionsByPeriod({ startDate, endDate } = {}) {
        return api.get(WALLET_ROUTES.TRANSACTIONS_PERIOD, { params: { startDate, endDate } })
    },
    getActiveRules() {
        return api.get(WALLET_ROUTES.RULES_ACTIVE)
    },
    getApplicableDepositRules(amount) {
        return api.get(WALLET_ROUTES.RULES_DEPOSIT_APPLICABLE, { params: { amount } })
    },
    createRewardRule(ruleDto) {
        return api.post(WALLET_ROUTES.RULES, ruleDto)
    },
    enableRule(ruleId) {
        return api.put(WALLET_ROUTES.RULE_ENABLE.replace('{ruleId}', ruleId))
    },
    disableRule(ruleId) {
        return api.put(WALLET_ROUTES.RULE_DISABLE.replace('{ruleId}', ruleId))
    },
    // 透支管理相关API
    setOverdraftLimit({ amount, remark } = {}) {
        return api.post(WALLET_ROUTES.OVERDRAFT_SET_LIMIT, { amount, remark })
    },
    increaseOverdraftLimit({ amount, remark } = {}) {
        return api.post(WALLET_ROUTES.OVERDRAFT_INCREASE, { amount, remark })
    },
    decreaseOverdraftLimit({ amount, remark } = {}) {
        return api.post(WALLET_ROUTES.OVERDRAFT_DECREASE, { amount, remark })
    },
    // 购买SVIP会员
    purchaseSvip() {
        return api.post('/api/wallet/purchase-svip')
    }
}

// 地址相关API
export const addressApi = {
    // 获取用户地址列表, 方法为 GET，无需 userId
    getAddressList() {
        return api.get(ADDRESS_ROUTES.LIST_ADDRESSES);
    },

    // 添加地址
    addAddress(addressInfo) {
        return api.post(ADDRESS_ROUTES.SAVE_ADDRESS, addressInfo)
    },
    
    // 获取单个地址详情（从列表中过滤）
    async getAddressById(addressId) {
        console.log('获取地址详情，ID:', addressId);
        // 获取所有地址，然后过滤出特定ID的地址
        const addresses = await api.get(ADDRESS_ROUTES.LIST_ADDRESSES);
        console.log('获取到的所有地址:', addresses);
        if (!addresses || !Array.isArray(addresses)) {
            throw new Error('获取地址列表失败');
        }
        
        // 找到匹配ID的地址
        const address = addresses.find(addr => addr.id == addressId);
        if (!address) {
            throw new Error(`未找到ID为${addressId}的地址`);
        }
        
        return address;
    },

    // 更新地址, 方法为 PUT，ID 在 URL 路径中，更新数据在请求体中
    updateAddress(addressId, addressInfo) {
        return api.put(`${ADDRESS_ROUTES.UPDATE_ADDRESS}/${addressId}`, addressInfo);
    },

    // 删除地址, 方法为 DELETE，ID 在 URL 路径中
    removeAddress(addressId) {
        return api.delete(`${ADDRESS_ROUTES.REMOVE_ADDRESS}/${addressId}`);
    }
}

// 导出默认的axios实例（用于特殊情况）
export default api
